import { Button, Card, Popconfirm } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { useEffect, useState } from 'react';

import userService from '@/api/services/userService';
import { IconButton, Iconify } from '@/components/icon';
import { usePathname, useRouter } from '@/router/hooks';
import ProTag from '@/theme/antd/components/tag';
import { useThemeToken } from '@/theme/hooks';

import UserModal, { type UserModalProps } from './components/userModel';

import type { Role, UserInfo } from '#/entity';
import { BasicStatus } from '#/enum';

enum ModelType {
  CREATE = '创建',
  UPDATE = '编辑',
}
export default function RolePage() {
  const { colorTextSecondary } = useThemeToken();
  const { push } = useRouter();
  const pathname = usePathname();
  const [users, setUsers] = useState<UserInfo[]>([]);
  const [loading, setLoading] = useState(false);

  const [userModalPros, setUserModalPros] = useState<UserModalProps>({
    id: null,
    title: '新建用户',
    show: false,
    onCancel: () => {
      setUserModalPros((prev) => ({ ...prev, show: false, id: null }));
    },
  });

  const onCreate = () => {
    setUserModalPros((prev) => ({
      ...prev,
      show: true,
      title: `${ModelType.CREATE}用户`,
    }));
  };

  const onEdit = (item: any): any => {
    console.log(item, 'item');
    setUserModalPros((prev) => ({
      ...prev,
      formValue: item,
      id: item.id,
      show: true,
      title: `${ModelType.UPDATE}用户`,
    }));
  };

  const columns: ColumnsType<UserInfo> = [
    {
      title: '用户名',
      dataIndex: 'name',
      width: 300,
      render: (_, record) => {
        return (
          <div className="flex">
            <img alt="" src={record.avatar} className="h-10 w-10 rounded-full" />
            <div className="ml-2 flex flex-col">
              <span className="text-sm">{record.account}</span>
              <span style={{ color: colorTextSecondary }} className="text-xs">
                {record.email}
              </span>
            </div>
          </div>
        );
      },
    },
    {
      title: '角色',
      dataIndex: 'role',
      align: 'center',
      width: 120,
      render: (role: Role) => <ProTag color="cyan">{role.name}</ProTag>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 120,
      render: (status) => (
        <ProTag color={status === BasicStatus.DISABLE ? 'error' : 'success'}>
          {status === BasicStatus.DISABLE ? 'Disable' : 'Enable'}
        </ProTag>
      ),
    },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 100,
      render: (_, record) => (
        <div className="flex w-full justify-center text-gray">
          <IconButton
            onClick={() => {
              push(`${pathname}/${record.id}`);
            }}
          >
            <Iconify icon="mdi:card-account-details" size={18} />
          </IconButton>
          <IconButton onClick={() => onEdit(record)}>
            <Iconify icon="solar:pen-bold-duotone" size={18} />
          </IconButton>
          <Popconfirm
            title="确认删除此用户?"
            okText="确认"
            cancelText="取消"
            placement="left"
            onConfirm={async () => {
              console.log('delete user');
              await userService.deleteById(record.id);
              getList();
            }}
          >
            <IconButton>
              <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
            </IconButton>
          </Popconfirm>
        </div>
      ),
    },
  ];
  useEffect(() => {
    getList();
  }, []);

  const getList = async () => {
    setLoading(true);
    const list = await userService.getList();
    setUsers(list);
    setLoading(false);
  };

  return (
    <Card
      title="User List"
      extra={
        <div className="flex w-full justify-center text-gray">
          <IconButton>
            <Iconify icon="mdi:reload" size={18} onClick={getList} />
          </IconButton>

          <Button type="primary" onClick={onCreate}>
            新建
          </Button>
        </div>
      }
    >
      <Table
        rowKey="id"
        size="small"
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={false}
        columns={columns}
        dataSource={users}
      />
      <UserModal {...userModalPros} />
    </Card>
  );
}
